from django.shortcuts import render, redirect, HttpResponse
from aj.ajgl import model_form1
from aj.ajgl import models1
import datetime
from aj.ajgl.page import Pagination
from django.db.models import Q

import numpy as np
import pandas as pd
from django_pandas.io import read_frame

pd.set_option('expand_frame_repr', False)


# 返回文字版日期
def date_gsh(t1, t2):
    t1 = datetime.datetime.strptime(t1, '%Y-%m-%d')
    t2 = datetime.datetime.strptime(t2, '%Y-%m-%d')
    return '{0}年{1}月{2}日至{3}年{4}月{5}日'.format(t1.year, t1.month, t1.day, t2.year, t2.month, t2.day)


# 返回obj
def get_obj(request):
    t1 = request.GET.get('t1') if request.GET.get('t1') else '{0}-01-01'.format(datetime.datetime.now().year)
    t2 = request.GET.get('t2') if request.GET.get('t2') else datetime.datetime.now().strftime('%Y-%m-%d')
    tj = request.GET.get('tj')
    cxtj = {}  # 查询条件
    s = request.GET.get('s')
    obj = models1.Anjian.objects.all().order_by("-id")  # 全部
    if s:
        cxtj['shi'] = s
    if request.user.category == '1' and request.user.level == '1':  # 省级管理员
        pass
    if request.user.category == '1' and request.user.level == '2':  # 市级管理员
        QQ = Q(aj_user__organization=request.user.organization) | Q(
            aj_user__organization__sj=request.user.organization.id)
        obj = obj.filter(QQ)
    if request.user.category == '1' and request.user.level == '3':  # 县级管理员
        obj = obj.filter(aj_user__organization=request.user.organization)
    if request.user.category == '2':  # 普通用户
        obj = obj.filter(aj_user=request.user)
    if t1:
        cxtj['aj_time1__range'] = [datetime.datetime.strptime(t1, "%Y-%m-%d"),
                                   datetime.datetime.strptime(t2, "%Y-%m-%d")]
        obj = obj.filter(**cxtj)  # 日期筛选
    if tj:
        QQ = Q(aj_anyou__contains=tj) | Q(aj_dangshiren__contains=tj) | Q(aj_faren__contains=tj)
        obj = obj.filter(QQ)  # 条件筛选
    return obj


# 将df转换成前端可用数据
def get_ajbb_df(df, x, y):
    if x == 'shi':
        df_id = pd.DataFrame({x: ['郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '濮阳市', '许昌市', '漯河市', '三门峡市',
                                  '南阳市', '商丘市', '信阳市', '周口市', '驻马店市', '济源市', '巩义市', '兰考县', '汝州市', '滑县', '长垣市', '邓州市',
                                  '永城市', '固始县', '鹿邑县', '新蔡县', '河南省', '合计'], 'bj': range(30)})
    elif x == 'aj_zhonglei':
        df_id = pd.DataFrame({x: ['动监', '畜牧', '饲料', '兽药', '屠宰', '种子', '肥料', '生鲜乳', '农产品', '农机管理', '渔业水产',
                                  '资源利用', '农业转基因', '其他'], 'bj': range(14)})
    df0 = pd.pivot_table(df, index=x, aggfunc='sum')  # 处罚金额  涉案金额
    df1 = pd.pivot_table(df, index=x, aggfunc='count', columns='aj_heiwodian', values='sheng', fill_value=0)  # 是否黑窝点
    df2 = pd.pivot_table(df, index=x, aggfunc='count', columns='aj_zhuangtai', values='sheng', fill_value=0)  # 移交输
    df3 = pd.pivot_table(df, index=x, aggfunc='count', values=['aj_time1', 'aj_time2'], fill_value=0)  # 立案数,结案数
    if x == 'xian':
        df = df0.merge(df1, on=x).merge(df2, on=x).merge(df3, on=x)
        df.reset_index(drop=False, inplace=True)
    else:
        df = df0.merge(df1, on=x).merge(df2, on=x).merge(df3, on=x).merge(df_id, on=x)
        df.sort_values('bj', inplace=True)
    df.rename(columns={x: y, 'aj_chufajine': '罚款总金额（万元）', 'aj_sheanjine': '涉案总金额（万元）', '是': '捣毁黑窝点数', 'aj_time1': '立案数',
                       'aj_time2': '结案数', '移交司法': '移交司法数', }, inplace=True)

    for i in ['移交司法数', '结案数', '罚款总金额（万元）', '捣毁黑窝点数']:
        if i not in df.columns:
            df[i] = 0
    df_sum = df.sum()
    df_sum[0] = '合计'
    df = df.append(df_sum, ignore_index=True)
    df = df[[y, '立案数', '结案数', '移交司法数', '涉案总金额（万元）', '罚款总金额（万元）', '捣毁黑窝点数']]
    return df.to_dict(orient='split')


# 将首页的数据转换成模板能用的
def get_index_df(df):
    df_id = pd.DataFrame({'shi': ['郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '濮阳市', '许昌市', '漯河市', '三门峡市',
                                  '南阳市', '商丘市', '信阳市', '周口市', '驻马店市', '济源市', '巩义市', '兰考县', '汝州市', '滑县', '长垣市', '邓州市',
                                  '永城市', '固始县', '鹿邑县', '新蔡县'],
                          'jx': ['郑州', '开封', '洛阳', '平顶山', '安阳', '鹤壁', '新乡', '焦作', '濮阳', '许昌', '漯河', '三门峡', '南阳', '商丘',
                                 '信阳', '周口', '驻马店', '济源', '巩义', '兰考', '汝州', '滑县', '长垣', '邓州', '永城', '固始', '鹿邑', '新蔡'],
                          'bj': range(28)})
    df_ajxl = pd.DataFrame({'aj_zhonglei': ['动监', '畜牧', '饲料', '兽药', '屠宰', '生鲜乳', '种子', '肥料', '农产品', '农机管理', '渔业水产',
                                            '资源利用', '农业转基因', '其他'],
                            'aj_dl': ['畜牧兽医案件', '畜牧兽医案件', '畜牧兽医案件', '畜牧兽医案件', '畜牧兽医案件', '畜牧兽医案件', '农业案件', '农业案件',
                                      '农业案件', '农机案件', '渔业案件', '资源利用案件', '转基因案件', '其他案件'],
                            'bj1': range(14)})  # 案件小类
    df_ajdl = pd.DataFrame(
        {'aj_dl': ['畜牧兽医案件', '农业案件', '农机案件', '渔业案件', '资源利用案件', '转基因案件', '其他案件'], 'bj2': range(7)})  # 案件打雷
    obj = {}

    obj['ajzs'] = df.id.count()  # 案件总数
    obj['jas'] = df.aj_time2.count()  # 结案数
    obj['saje'] = df.aj_sheanjine.sum()  # 涉案金额
    obj['cfje'] = df.aj_chufajine.sum()  # 处罚金额
    obj['yjs'] = df[df['aj_zhuangtai'] == '移交司法'].id.count()  # 移交司法数
    obj['yjjes'] = df[df['aj_zhuangtai'] == '移交司法'].aj_sheanjine.sum()  # 移交司法金额
    obj['hwds'] = df[df['aj_heiwodian'] == '是'].id.count()  # 黑窝点数

    df_1 = pd.pivot_table(df, index='shi', aggfunc='count', values=['aj_time1', 'aj_time2'],
                          fill_value=0)  # 按地市统计立案数，结案数
    df_2 = pd.pivot_table(df, index='shi')  # 按地市统计金额
    df_1 = df_1.merge(df_id, how='right', on='shi').fillna(0).sort_values('bj')
    df_2 = df_2.merge(df_id, how='right', on='shi').fillna(0).sort_values('bj')
    if 'aj_chufajine' not in df_2.columns:
        df_2['aj_chufajine']=0
    obj['pic1'] = df_1[['jx', 'shi', 'aj_time1', 'aj_time2']].to_dict(orient='list')
    obj['pic1_max']=(int(max(df_1['aj_time1'])/10)+1)*10
    obj['pic2'] = df_2[['jx', 'aj_chufajine', 'aj_sheanjine']].to_dict(orient='list')
    obj['pic2_max'] = (int(max(max(df_2['aj_chufajine']),max(df_2['aj_sheanjine'])) / 10) + 1) * 10

    df_3 = df.pivot_table(index='aj_zhonglei', values='aj_time1', aggfunc='count').merge(df_ajxl,on='aj_zhonglei').sort_values('bj1')
    df_4 = df_3.pivot_table(index='aj_dl', values='aj_time1', aggfunc='sum').merge(df_ajdl, on='aj_dl').sort_values('bj2')
    df_3 = df_3.to_dict(orient='split')
    df_4 = df_4.to_dict(orient='split')
    obj['pic3_1'] = [{"name": v[0], "value": v[1]} for v in df_3['data']]
    obj['pic3_2'] = [{"name": v[0], "value": v[1]} for v in df_4['data']]

    obj['pic4'] =[{"name": v, "value": int(obj['pic1']['aj_time1'][i])} for i, v in enumerate(obj['pic1']['shi'])]
    obj['pic4_max'] = max(obj['pic1']['aj_time1'])
    return obj


# 案件管理首页
def index(request):
    obj = get_obj(request)
    obj = get_index_df(read_frame(obj))
    return render(request, 'html模板/案件index.html', locals())


# 立案信息
def add(request):
    if request.method == "POST":
        obj = model_form1.Anjian_li(request, request.POST)
        if obj.is_valid():
            u = request.user.organization.xingzhengquhua
            bcxx = {"sheng": u.sheng, "shi": u.shi, "xian": u.xian, "aj_user": request.user}  # 补充信息
            models1.Anjian.objects.create(**{**obj.cleaned_data, **bcxx})
            return redirect('/ajlist/')
        else:
            return render(request, 'html模板/案件新增.html', locals())
    obj = model_form1.Anjian_li(request)
    return render(request, 'html模板/案件新增.html', locals())


# 结案信息
def jie(request, id):
    edit_obj = models1.Anjian.objects.filter(id=id).first()
    if request.method == "POST":
        obj = model_form1.Anjian_jie(request, request.POST, instance=edit_obj)
        if edit_obj.aj_user_id != request.user.id:
            msg = "立案信息的添加这才有权限修改！"
            return render(request, 'html模板/案件结案.html', locals())
        if obj.is_valid():
            obj.save()
            return redirect('/ajlist/')
        else:
            return render(request, 'html模板/案件结案.html', locals())
    obj = model_form1.Anjian_jie(request, instance=edit_obj)
    pic_list = models1.Pic.objects.filter(Anjian_id=id)
    return render(request, 'html模板/案件结案.html', locals())


# 案件统计报表
def ajbb(request):
    if not request.user.category == '1':
        return HttpResponse('普通执法人员没有权利查看此信息。')
    obj = get_obj(request)
    if obj:
        if request.user.level == '1' and not request.GET.get('s'):  # 省级的，以省辖市统计
            obj1 = get_ajbb_df(read_frame(obj), 'shi', '省辖市')
        else:  # 市县两级管理员和省级管理员下探下级的，均以县为单位来统计
            obj1 = get_ajbb_df(read_frame(obj), 'xian', '市（县、区）')
        obj2 = get_ajbb_df(read_frame(obj), 'aj_zhonglei', '案件类型')
    return render(request, 'html模板/案件统计报表.html', locals())


# 案件详细列表
def ajlist(request):
    obj = get_obj(request)
    current_page = request.GET.get('p')
    page_obj = Pagination(obj.count(), current_page, perPageItemNum=20, qianzhui='index/1', maxPageNum=9)
    list = obj[page_obj.start():page_obj.end()]
    return render(request, 'html模板/案件详细列表.html', locals())


from django.http import JsonResponse


def del_aj(request, id):
    ret = {'status': 1}
    cxtj = {}
    cxtj['id'] = id
    del_obj = models1.Anjian.objects.filter(id=id)
    if request.user.category == '1':
        cxtj['xian'] = request.user.organization.xingzhengquhua.xian
    else:
        cxtj['aj_user'] = request.user
    del_obj = models1.Anjian.objects.filter(**cxtj).first()
    if del_obj:
        del_obj.delete()
    else:
        ret['status'] = 2
    return JsonResponse(ret)


from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def upload_jaws(request, id):
    if request.method == "POST":
        avatar_img = request.FILES.get("pic")
        models1.Pic.objects.create(pic=avatar_img, Anjian_id=id)
        ret = {"status": 100, "msg": "100"}
        return JsonResponse(ret)
